<template>
  <div>
    <h1>我的信息</h1>
    <div>
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
      >
        <el-form-item label="用户名">
          <el-input v-model="ruleForm.userName" disabled />
        </el-form-item>
        <el-form-item label="密码" prop="userPass">
          <el-input v-model="ruleForm.userPass" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="nickName">
          <el-input v-model="ruleForm.nickName" />
        </el-form-item>
        <el-form-item label="手机号" prop="userMobile">
          <el-input v-model="ruleForm.userMobile" />
        </el-form-item>
        <el-form-item label="邮箱" prop="userEmail">
          <el-input v-model="ruleForm.userEmail" />
        </el-form-item>
        <el-form-item label="头像" prop="count">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:10010/user/index/loadImage"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :headers="headers"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            保存
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">清除</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import type { UploadProps } from "element-plus";
import { getUserByUserId, updateUser } from "../api/api";

const imageUrl = ref("");
const headers = ref({
  token: sessionStorage.getItem("token"),
});
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  //   imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  imageUrl.value = response.data;
};

const ruleFormRef = ref<FormInstance>();
const ruleForm = ref({
  userName: "",
  userPass: "",
  nickName: "",
  userMobile: "",
  userEmail: "",
  userAvatar: null,
});
const locationOptions = ["Home", "Company", "School"];

const rules = reactive<FormRules>({
  userPass: [
    { required: true, message: "请输入密码", trigger: "blur" },
    {
      pattern: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9]{6,}$/,
      message: "密码包含大小写字母和数字，最少6位",
      trigger: "blur",
    },
  ],
  nickName: [
    { required: true, message: "请输入真实姓名", trigger: "blur" },
    {
      pattern: /^[\u4e00-\u9fa5]{0,}$/,
      message: "必须为汉字",
      trigger: "blur",
    },
  ],
  userMobile: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern:
        /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  userEmail: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    {
      pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
      message: "请输入正确的邮箱",
      trigger: "blur",
    },
  ],
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      ruleForm.value.userAvatar = imageUrl.value;
      updateUser(ruleForm.value).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("修改成功");
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

onMounted(() => {
  let user = sessionStorage.getItem("user");
  let u = JSON.parse(user);
  getUserByUserId(u.userId).then((res) => {
    ruleForm.value = res.data.data;
    console.log(res.data.data);

    imageUrl.value = res.data.data.userAvatar;
  });
});
</script>

<!-- 图片样式 -->
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
